<template>
  <view class="member-list-component">
    <!-- 会员列表 -->
    <view v-if="loading && memberList.length === 0" class="loading-container">
      <wd-loading size="large" />
      <text class="loading-text">加载中...</text>
    </view>

    <view v-else-if="!loading && memberList.length === 0" class="empty-container">
      <wd-icon name="user" size="60px" color="#ccc" />
      <text class="empty-text">暂无会员数据</text>
    </view>

    <scroll-view
      v-else
      scroll-y
      class="member-scroll"
      refresher-enabled
      :refresher-triggered="refreshing"
      @scrolltolower="handleLoadMore"
      @refresherrefresh="handleRefresh"
    >
      <view v-for="member in memberList" :key="member.id" class="member-item">
        <view class="member-info">
          <view class="member-name">{{ member.username || member.name || "未填写姓名" }}</view>
          <view class="member-phone">{{ member.mobile || member.phone || "未填写手机号" }}</view>
          <view class="member-time">
            加入时间：{{ formatDate(member.createTime || member.joinTime) }}
          </view>
          <view class="member-id">与关联人的关系：{{ member.id }}</view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view v-if="loading && memberList.length > 0" class="load-more">
        <wd-loading size="small" />
        <text>加载中...</text>
      </view>

      <view v-else-if="hasMore && !loading" class="load-more" @click="handleLoadMore">
        <text>点击加载更多</text>
      </view>

      <view v-else-if="memberList.length > 0" class="no-more">
        <text>没有更多了</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";

// Props 定义
interface Props {
  apiMethod?: (params: any) => Promise<any>;
  searchKeyword?: string;
  pageSize?: number;
  autoLoad?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  apiMethod: undefined,
  searchKeyword: "",
  pageSize: 10,
  autoLoad: true,
});

// Emits 定义
const emit = defineEmits<{
  memberClick: [member: any];
  loadMore: [page: number];
  refresh: [];
}>();

// 响应式数据
const loading = ref(false);
const hasMore = ref(true);
const pageNum = ref(1);
const refreshing = ref(false);
const total = ref(0);
const memberList = ref<any[]>([]);

const defaultAvatar = ref("https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/e73f70149e504ceca250fb288ca891b4.png");

// 监听搜索关键词变化
watch(
  () => props.searchKeyword,
  () => {
    handleSearch();
  }
);

// 模拟数据
const mockMembers = [
  {
    id: "父亲",
    username: "张三",
    mobile: "13800138001",
    createTime: "2024-01-15",
    avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/e73f70149e504ceca250fb288ca891b4.png",
    status: 1,
  },
  {
    id: "女儿",
    username: "李四",
    mobile: "13800138002",
    createTime: "2024-01-14",
    avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/e73f70149e504ceca250fb288ca891b4.png",
    status: 0,
  },
  {
    id: "女儿",
    username: "张三",
    mobile: "13800138001",
    createTime: "2024-01-15",
    avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/e73f70149e504ceca250fb288ca891b4.png",
    status: 1,
  },
  {
    id: "孙子",
    username: "李四",
    mobile: "13800138002",
    createTime: "2024-01-14",
    avatar: "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/e73f70149e504ceca250fb288ca891b4.png",
    status: 0,
  },
];

// 方法定义
const loadMembers = async (loadMore = false) => {
  if (!props.apiMethod) {
    // 使用模拟数据
    if (!loadMore && !refreshing.value) {
      loading.value = true;
    }

    try {
      // 模拟网络延迟
      await new Promise((resolve) => setTimeout(resolve, 500));

      const queryParams = {
        pageNum: pageNum.value,
        pageSize: props.pageSize,
        ...(props.searchKeyword && { name: props.searchKeyword }),
      };

      // 模拟搜索过滤
      let filteredData = [...mockMembers];
      if (props.searchKeyword) {
        filteredData = filteredData.filter((item) => item.username.includes(props.searchKeyword));
      }

      // 模拟分页
      const startIndex = (queryParams.pageNum - 1) * queryParams.pageSize;
      const endIndex = startIndex + queryParams.pageSize;
      const paginatedData = filteredData.slice(startIndex, endIndex);

      const totalCount = filteredData.length;
      total.value = totalCount;

      const processedList = paginatedData.map((item: any) => ({
        ...item,
        id: item.id || item.userId,
        username: item.username || item.name || "未填写姓名",
        mobile: item.mobile || item.phone || "未填写手机号",
        createTime: item.createTime || item.joinTime,
        avatar: item.avatar || item.headImg || defaultAvatar.value,
        status: item.status || item.auditStatus || 0,
      }));

      if (loadMore) {
        memberList.value.push(...processedList);
      } else {
        memberList.value = processedList;
      }

      // 判断是否还有更多数据
      hasMore.value = memberList.value.length < total.value;

      // 触发加载更多事件
      if (loadMore) {
        emit("loadMore", pageNum.value);
      }
    } catch (error) {
      console.error("加载会员数据失败:", error);
      uni.showToast({
        title: error.message || "加载失败",
        icon: "none",
      });
    } finally {
      loading.value = false;
    }
    return;
  }

  // 真实接口调用
  if (!loadMore && !refreshing.value) {
    loading.value = true;
  }

  try {
    const queryParams = {
      pageNum: pageNum.value,
      pageSize: props.pageSize,
      ...(props.searchKeyword && { name: props.searchKeyword }),
    };

    const response = await props.apiMethod(queryParams);

    if (response.code === 200) {
      const { rows = [], total: totalCount = 0 } = response;
      total.value = totalCount;

      const processedList = rows.map((item: any) => ({
        ...item,
        id: item.id || item.userId,
        username: item.username || item.name || "未填写姓名",
        mobile: item.mobile || item.phone || "未填写手机号",
        createTime: item.createTime || item.joinTime,
        avatar: item.avatar || item.headImg || defaultAvatar.value,
        status: item.status || item.auditStatus || 0,
      }));

      if (loadMore) {
        memberList.value.push(...processedList);
      } else {
        memberList.value = processedList;
      }

      // 判断是否还有更多数据
      hasMore.value = memberList.value.length < total.value;

      // 触发加载更多事件
      if (loadMore) {
        emit("loadMore", pageNum.value);
      }
    } else {
      throw new Error(response.msg || "获取数据失败");
    }
  } catch (error) {
    console.error("加载会员数据失败:", error);
    uni.showToast({
      title: error.message || "加载失败",
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

const handleLoadMore = () => {
  if (!hasMore.value || loading.value || refreshing.value) return;

  pageNum.value++;
  loadMembers(true);
};

const handleRefresh = async () => {
  refreshing.value = true;
  pageNum.value = 1;
  hasMore.value = true;

  try {
    await loadMembers();
    emit("refresh");
  } finally {
    refreshing.value = false;
  }
};

const handleSearch = () => {
  pageNum.value = 1;
  hasMore.value = true;
  memberList.value = [];
  loadMembers();
};

const handleViewDetail = (member: any) => {
  emit("memberClick", member);
};

const handleAvatarClick = (member: any) => {
  emit("memberClick", member);
};

// 状态处理
const getStatusText = (status: number | string) => {
  const statusMap: Record<string, string> = {
    0: "待审核",
    1: "已激活",
    2: "已禁用",
    pending: "待审核",
    active: "已激活",
    inactive: "已禁用",
  };
  return statusMap[status] || "未知";
};

const getStatusClass = (status: number | string) => {
  const statusMap: Record<string, string> = {
    0: "status-pending",
    1: "status-active",
    2: "status-inactive",
    pending: "status-pending",
    active: "status-active",
    inactive: "status-inactive",
  };
  return statusMap[status] || "status-pending";
};

const formatDate = (dateStr: string) => {
  if (!dateStr) return "";
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
};

// 暴露方法给父组件
const refresh = () => {
  handleRefresh();
};

const reset = () => {
  pageNum.value = 1;
  hasMore.value = true;
  memberList.value = [];
  loadMembers();
};

// 生命周期
onMounted(() => {
  if (props.autoLoad) {
    loadMembers();
  }
});

// 暴露给父组件的方法
defineExpose({
  refresh,
  reset,
  loadMembers,
});
</script>

<style lang="scss" scoped>
.member-list-component {
  flex: 1;
  padding-top: 2.4rem;
  .loading-container,
  .empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;

    .loading-text,
    .empty-text {
      margin-top: 20rpx;
      font-size: 28rpx;
      color: #666;
    }
  }

  .member-scroll {
    height: 100%;
    max-height: 24rem;
    min-height: 10rem;
  }

  .member-item {
    display: flex;
    align-items: center;
    padding: 30rpx;
    background-color: #fff;
    margin: 0 20rpx 20rpx;
    border-radius: 12rpx;
    // box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    border: 1px solid #f0f0f0;
    .member-avatar {
      margin-right: 20rpx;
    }

    .member-info {
      flex: 1;

      .member-name {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 8rpx;
      }

      .member-phone {
        font-size: 26rpx;
        color: #666;
        margin-bottom: 4rpx;
      }

      .member-time {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 4rpx;
      }

      .member-id {
        font-size: 22rpx;
        color: #ccc;
      }
    }

    .member-actions {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      gap: 10rpx;

      .status-tag {
        font-size: 24rpx;
        padding: 4rpx 12rpx;
        border-radius: 12rpx;

        &.status-active {
          color: #52c41a;
          background-color: #f6ffed;
        }

        &.status-pending {
          color: #faad14;
          background-color: #fff7e6;
        }

        &.status-inactive {
          color: #ff4d4f;
          background-color: #fff2f0;
        }
      }
    }
  }

  .load-more,
  .no-more {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 30rpx;
    font-size: 24rpx;
    color: #999;

    &:active {
      opacity: 0.7;
    }
  }

  .load-more {
    cursor: pointer;
  }
}
</style>
